<?php











namespace app\admin\model;











use think\facade\Db;
use app\crm\model\OrderStatistics;
use app\admin\model\ShopModel;







class ShopOrderModel extends Common



{



    /**



     * @var string



     */



    protected $name = 'shop_order';







    protected $defaultSoftDelete = 0;







    protected $autoWriteTimestamp = true;







    /**



     * 驼峰格式转换



     * @var bool



     */



    protected $convertNameToCamel = true;







    protected $fail;







    /**



     * @author ran



     * @date 2021-12-10 20:01



     * mailbox 466180170@qq.com



     */



    public function getpayTimeAttr($value)



    {



        return date('Y-m-d', $value);



    }







    /**



     * @return \think\model\relation\HasOne



     * @author ran



     * @date 2021-12-04 15:28



     * mailbox 466180170@qq.com



     */



    public function person()



    {



        return $this->hasOne(PersonModel::class, 'id', 'sale_id')->field('id,name,position_name');



    }







    public function shopOrderGoods()



    {



        return $this->hasMany(ShopOrderGoodsModel::class, 'order_id', 'id')->field('id,order_id,goods_name,goods_id,pay_price,number');



    }







    /**



     * @param $ids



     * @author ran



     * @date 2021-12-04 13:53



     * mailbox 466180170@qq.com



     */



    public function getShopPersonOrder($request,$field, $ids)



    {



        $connect = $this->with(['shopOrderGoods'])->field($field)->where('is_pay', 1)



            ->whereIn('sale_id', $ids)



            ->when($request['month'] ?? [], function ($query) use ($month) {



                return $query->whereMonth('create_time', $month);



            })->select();



        return empty($connect) ? array() : $connect->toArray();



    }







    /**



     * @author ran



     * @date 2021-12-04 15:41



     * mailbox 466180170@qq.com



     */



    public function getShopOrderGroupBySaleId($page = 1, $limit = 20)



    {



        $connect = $this->with('person')->field(['sale_id'])->



        where('is_pay', 1)->group('sale_id');



        return empty($connect) ? ['count' => $connect->count(), 'list' => []] : ['count' => $connect->count(), 'list' => $connect->page($page, $limit)->select()->toArray()];



    }







    /**



     *



     * @author ran



     * @date 2021-12-10 19:30



     * mailbox 466180170@qq.com



     */



    public function getAdminShopOrderCapital(int $page, int $limit)



    {



        $field = 'uid,shop_name,consignee,sum(pay_amount) as amount,pay_time,sale_name';



        $connect = $this->field($field)->where('is_pay', 1)->group('uid')->order('pay_time', 'desc');



        return empty($connect) ? ['count' => $connect->count(), 'list' => []] : ['count' => $connect->count(), 'list' => $connect->page($page, $limit)->select()->toArray()];



    }







    /**



     * 获取订单公共条件



     * @param $shopIds



     * @param $request



     * @author ran



     * @date 2021-11-18 10:52



     * mailbox 466180170@qq.com



     */



    public function getShopOrderCommonDataCollect($shopIds, $request)
    {
        $pc = $request['pc'] ?? 0;

        $isShop = $request['isShop'] ?? 0;

        $startTime = strtotime($request['startTime'] ?? 0);



        $endTime = strtotime($request['endTime'] ?? 0);



        $sysDealNumber = $this->getShopOrderCollect('count', $shopIds, $startTime, $endTime, $isShop);

        $sysDealNumberEcharts = $this->getShopOrderCollect('echarts', $shopIds, $startTime, $endTime, $isShop);

        if($pc == 1){

            return $sysDealNumberEcharts;
            exit;

        }

        $sysNewOderAmountList = $this->getShopNewOrderAmount($shopIds, $startTime, $endTime, $isShop);

		$sysCompleteNewOrder = $sysNewOderAmountList['newOrder'];
		//$sysCompleteNewOrder = $this->getShopNewOrderAmount($shopIds, $startTime, $endTime, $isShop);

        //$sysCompleteNewOrder = $this->getShopOrderCollect('newOrder', $shopIds, $startTime, $endTime, $isShop);

		//$sysCompleteSupplement = $this->getShopOrderCollect('repairOrder', $shopIds, $startTime, $endTime, $isShop);
		$sysCompleteSupplement = $sysNewOderAmountList['repairOrder'];
        //$sysCompleteSupplement = $this->getShopRepairOrderAmount($shopIds, $startTime, $endTime, $isShop);


		//$sysCurrentPerformance = $this->getShopOrderCollect('amount', $shopIds, $startTime, $endTime, $isShop);

		$sysCurrentPerformance = bcadd($sysCompleteNewOrder,$sysCompleteSupplement,2);

        return compact('sysCompleteNewOrder','sysCompleteSupplement','sysDealNumber', 'sysDealNumberEcharts', 'sysCurrentPerformance');



    }



    /**



     * 根据场景值获取订单数据集合



     * @param $scene



     * @param $shopIds



     * @param $startTime



     * @param $endTime



     * @author ran



     * @date 2021-11-18 11:27



     * mailbox 466180170@qq.com



     */



    public function getShopOrderCollect($scene, $shopIds, $startTime, $endTime, $isShop)

    {
        // echo "门店or门诊".$isShop;
        // 2022-5-8 更新
        $is_shop_where = [];
        $mzShopID = [73782775377728,73782775392774,73782775206631,73782775131388,73782775085647,73782774991693,73782774881835];
        if($isShop){
            // echo "管理员查看";
            if($isShop=='1'){
                array_push($is_shop_where,['shop_id','not in',$mzShopID]);
            }else{
                array_push($is_shop_where,['shop_id','in',$mzShopID]);
            }
        }else{
            // echo "门店查看";
        }
        // exit;

        $connect = Db::name('shop_refund_order')

            ->when($shopIds ?? [], function ($query) use ($shopIds) {

                return $query->whereIn('shop_id', $shopIds);

            })

            ->when($startTime ?? 0, function ($query) use ($startTime) {

                return $query->whereTime('deal_time', '>=', $startTime);

            })

            ->when($endTime ?? 0, function ($query) use ($endTime) {

                return $query->whereTime('deal_time', '<=', $endTime);

            },function ($query) use ($endTime) {

                return $query->whereMonth('deal_time');

            })->where('status','<>',3)
            ->where($is_shop_where);// 2022-5-8 更新

        switch ($scene) {

            case 'count':

                return Db::name('customer')->where($is_shop_where)

                    ->when($shopIds ?? [], function ($query) use ($shopIds) {

                        return $query->whereIn('shop_id', $shopIds);

                    })

                    ->when($startTime ?? 0, function ($query) use ($startTime) {

                        return $query->whereTime('cj_time', '>=', $startTime);

                    })

                    ->when($endTime ?? 0, function ($query) use ($endTime) {

                        return $query->whereTime('cj_time', '<=', $endTime);

                    },function ($query) use ($endTime) {

                        return $query->whereMonth('cj_time');

                    })

                    ->where('cj_money','>',0)

                    ->count();

                break;

            case 'echarts':

                $customerIds = Db::name('customer')->where($is_shop_where)

                ->when($shopIds ?? [], function ($query) use ($shopIds) {

                    return $query->whereIn('shop_id', $shopIds);

                })

                ->when($startTime ?? 0, function ($query) use ($startTime) {

                    return $query->whereTime('cj_time', '>=', $startTime);

                })

                ->when($endTime ?? 0, function ($query) use ($endTime) {

                    return $query->whereTime('cj_time', '<=', $endTime);

                },function ($query) use ($endTime) {

                    return $query->whereMonth('cj_time');

                })

                ->where('cj_money','>',0)

                ->column('id');

                $bh = [1,2,3,4,5,6,7,8,655,656];

                $dd = [10];

                $xm = [9,11,12];

                $bhNum = Db::name('customer_scar')->where([['customer_id','in',$customerIds],['customer_setting_id_type','in',$bh]])->count();

                $ddNum = Db::name('customer_scar')->where([['customer_id','in',$customerIds],['customer_setting_id_type','in',$dd]])->count();

                $xmNum = Db::name('customer_scar')->where([['customer_id','in',$customerIds],['customer_setting_id_type','in',$xm]])->count();

                $data = [];

                $one['name'] = '疤痕成交';
                $one['value'] = $bhNum ?? 0;

                array_push($data,$one);

                $two['name'] = '痘痘成交';
                $two['value'] = $ddNum ?? 0;

                array_push($data,$two);

                $three['name'] = '项目成交';
                $three['value'] = $xmNum ?? 0;

                array_push($data,$three);

                return $data;

                break;

            case 'amount':

                //退款单

                $refund =$connect->where('type',1)

                    ->where('status','<>',3)

                    ->where('refund_type','<>','101.03')

                    ->sum('pay_amount');

                //收款单

                $new = Db::name('shop_refund_order')

                    ->where($is_shop_where)

                    ->where('refund_type','<>','101.03')

                    ->when($shopIds ?? [], function ($query) use ($shopIds) {

                        return $query->whereIn('shop_id', $shopIds);

                    })

                    ->when($startTime ?? 0, function ($query) use ($startTime) {

                        return $query->whereTime('deal_time', '>=', $startTime);

                    })

                    ->when($endTime ?? 0, function ($query) use ($endTime) {

                        return $query->whereTime('deal_time', '<=', $endTime);

                    },function ($query) use ($endTime) {

                        return $query->whereMonth('deal_time');

                    })

                    ->where('status','<>',3)

                    ->where('type',3)

                    ->sum('pay_amount');

                return $new -$refund;

                break;

            case 'newOrder':

                //退款单

                $refund =$connect->where('type',1)

                    ->where('status','<>',3)

                    ->where('refund_type','<>','101.03')

                    ->where('order_type',1)

                    ->sum('pay_amount');

                //收款单

                $new =Db::name('shop_refund_order')->where($is_shop_where)

                    ->when($shopIds ?? [], function ($query) use ($shopIds) {

                        return $query->whereIn('shop_id', $shopIds);

                    })

                    ->when($startTime ?? 0, function ($query) use ($startTime) {

                        return $query->whereTime('deal_time', '>=', $startTime);

                    })

                    ->when($endTime ?? 0, function ($query) use ($endTime) {

                        return $query->whereTime('deal_time', '<=', $endTime);

                    },function ($query) use ($endTime) {

                        return $query->whereMonth('deal_time');

                    })

                    ->where('refund_type','<>','101.03')

                    ->where('status','<>',3)

                    ->where('type',3)

                    ->where('order_type',1)

                    ->sum('pay_amount');

                return $new -$refund;

            case 'repairOrder':

                $refund =$connect->where('type',1)

                    ->where('status','<>',3)

                    ->where('refund_type','<>','101.03')

                    ->where('order_type',2)

                    ->sum('pay_amount');

                $new =Db::name('shop_refund_order')->where($is_shop_where)

                    ->when($shopIds ?? [], function ($query) use ($shopIds) {

                        return $query->whereIn('shop_id', $shopIds);

                    })

                    ->when($startTime ?? 0, function ($query) use ($startTime) {

                        return $query->whereTime('deal_time', '>=', $startTime);

                    })

                    ->when($endTime ?? 0, function ($query) use ($endTime) {

                        return $query->whereTime('deal_time', '<=', $endTime);

                    },function ($query) use ($endTime) {

                        return $query->whereMonth('deal_time');

                    })

                    ->where('refund_type','<>','101.03')

                    ->where('status','<>',3)

                    ->where('type',3)

                    ->where('order_type',2)

                    ->sum('pay_amount');

                return $new -$refund;

                break;

            default:

                break;

        }

    }


    public function miniHomeOrder($shopIds, $request)
    {
        $isShop = $request['isShop'] ?? 0;

        $startTime = $request['startTime'] ?? 0;

        $endTime = $request['endTime'] ?? 0;

        // echo $startTime."<br/>";
        // echo $endTime."<br/>";
        // exit;

        // $amount = $this->getShopOrderCollect('amount', $shopIds, $startTime, $endTime, $isShop);

        // $amountNew = $this->getShopOrderCollect('newOrder', $shopIds, $startTime, $endTime, $isShop);

        // $amountRepair = $this->getShopOrderCollect('repairOrder', $shopIds, $startTime, $endTime, $isShop);

        $order = $this->getShopNewOrderAmount($shopIds, $startTime, $endTime, $isShop);

        $amountNew = $order['newOrder'];

        $amountRepair = $order['repairOrder'];

        $amount = bcadd($amountNew,$amountRepair,2);


        return ['amount' => $amount,'amountNew' => $amountNew,'amountRepair' => $amountRepair];

    }


	/*
	@ 计算门店的新单和补单规则
	*/


	public function getShopNewOrderAmount($shopId, $startTime, $endTime, $isShop){

		$where = [];
		array_push($where, ['type', '<>', 2]);//只有直营店数据
		array_push($where, ['status', '=', 1]);//门店关闭状态
		array_push($where, ['shop_id', '<>', 74076159037951]);// 去掉营销中心
		
		// echo '<pre>';
		// print_r($shopId);exit;
		
		if(empty($shopId)){  //查询所有门店和门诊数据
			
			if($isShop==1){ // 
				array_push($where, ['shop_type', '=', 2]);//1是门诊 2是门店
			}else{
				array_push($where, ['shop_type', '=', 1]);//1是门诊 2是门店
			}
			
		}else{
			
			//echo '数据测试---';
			
			if($isShop==1){ //查询指定门店和门诊数据
			
				array_push($where, ['shop_type', '=', 2]);//1是门诊 2是门店
			}else{
				array_push($where, ['shop_type', '=', 1]);//1是门诊 2是门店
			}
			array_push($where, ['shop_id', 'in', $shopId]);
		}
		
		$shopList = Db::name('shop')->where($where)->column('shop_id,shop_name,shop_type,market_id');
		
		// if(empty($shopId)){
		// 	/*  @ 总部职能 查看权限 --- 1是默认 门店 2是 医院  */
		// 	if($isShop==1){
		// 		array_push($where, ['shop_type', '=', 2]);//1是门诊 2是门店
		// 		$shopList = Db::name('shop')->where($where)->column('shop_id,shop_name,shop_type,market_id');
		// 	}

		// 	if($isShop==2){
		// 		array_push($where, ['shop_type', '=', 1]);//1是门诊 2是门店
		// 		$shopList = Db::name('shop')->where($where)->column('shop_id,shop_name,shop_type,market_id');
		// 	}
		// }else{
		// 	$shopList = Db::name('shop')->where('shop_id','in', $shopId)->column('shop_id,shop_name,shop_type,market_id');
		// }
		
		// echo '<pre>';
		// print_r($shopList);exit;
		
		/* @ 门店或医院查看权限 */

		if(empty($isShop)){
			$shopListT = $shopId;
			$shopList = Db::name('shop')->where('shop_id', $shopListT[0])->column('shop_id,shop_name,shop_type,market_id');

		}

		// echo '<pre>';
		// print_r($shopList);exit;

		$totalNewAmount = 0;
		$totalRepairAmount = 0;
        $model = new OrderStatistics();
        $shopIds = array_column($shopList,"shop_id");


        $shopModel = new ShopModel();


        $mzXDMoneyAllOne = $shopModel->outpatientPerform($shopIds,1,$startTime,$endTime); //门诊新单业绩

        $mzBDMoneyAllTwo = $shopModel->outpatientPerform($shopIds,2,$startTime,$endTime); //门诊补单业绩

        $shopXDMoneyAllOne = $shopModel->shopPerform($shopIds,1,$startTime,$endTime);  //门店新单业绩

        $shopBDMoneyAllTwo = $shopModel->shopPerform($shopIds,2,$startTime,$endTime);  //门店补单业绩


        // $newsXDMoneyAll =$model->sumShopPayMoneyNewMZAll('XD',$shopIds,$startTime,$endTime);

        // $budanMoneyAll =$model->sumShopPayMoneyNewMZAll('BD',$shopIds,$startTime,$endTime);

        // $newsXDMoneyAllOne =$model->sumShopPayMoneyNewAll('XD',$shopIds,1,$startTime,$endTime);

        // $newsXDMoneyAllTwo =$model->sumShopPayMoneyNewAll('XD',$shopIds,2,$startTime,$endTime);

        // $budanMoneyAllOne =$model->sumShopPayMoneyNewAll('BD',$shopIds,1,$startTime,$endTime);

        // $budanMoneyAllTwo =$model->sumShopPayMoneyNewAll('BD',$shopIds,2,$startTime,$endTime);
		foreach ($shopList as $key=>$value) {


			// if($value['market_id'] == 8 || $value['market_id'] == 9 || $value['market_id'] == 10|| $value['market_id'] == 11)
			// {

			// 	//echo '非们都在的 ----'.$value['shop_id'];echo '<br/>';

			// 	// $newsXDMoney1 = $model->sumShopPayMoneyNewMZ('XD',$value['shop_id'],$value['shop_type'],$startTime,$endTime);
			// 	// $budanMoney1 = $model->sumShopPayMoneyNewMZ('BD',$value['shop_id'],$value['shop_type'],$startTime,$endTime);
            //     $newsXDMoney1 = empty($newsXDMoneyAll[$value['shop_id']])?0:$newsXDMoneyAll[$value['shop_id']];
            //     $budanMoney1 = empty($budanMoneyAll[$value['shop_id']])?0:$budanMoneyAll[$value['shop_id']];

			// 	$totalNewAmount +=$newsXDMoney1;
			// 	$totalRepairAmount +=$budanMoney1;

			// }else{

			// 	//echo '各位小筑们 你们在做什么呢--'.$value['shop_id'];echo '<br/>';
			// 	// $newsXDMoney2 = $model->sumShopPayMoneyNew('XD',$value['shop_id'],$value['shop_type'],$startTime,$endTime);
			// 	// $budanMoney2 = $model->sumShopPayMoneyNew('BD',$value['shop_id'],$value['shop_type'],$startTime,$endTime);
            //     if($value['shop_type'] == 1)
            //     {
            //         $newsXDMoney2 = empty($newsXDMoneyAllOne[$value['shop_id']])?0:$newsXDMoneyAllOne[$value['shop_id']];
            //         $budanMoney2 = empty($budanMoneyAllOne[$value['shop_id']])?0:$budanMoneyAllOne[$value['shop_id']];
            //     }else{
            //         $newsXDMoney2 = empty($newsXDMoneyAllTwo[$value['shop_id']])?0:$newsXDMoneyAllTwo[$value['shop_id']];
            //         $budanMoney2 = empty($budanMoneyAllTwo[$value['shop_id']])?0:$budanMoneyAllTwo[$value['shop_id']];
            //     }

			// 	$totalNewAmount +=$newsXDMoney2;
			// 	$totalRepairAmount +=$budanMoney2;
			// }

            if($value['shop_type'] == 1){
                //门诊
                $newsXDMoney = empty($mzXDMoneyAllOne[$value['shop_id']])?0:$mzXDMoneyAllOne[$value['shop_id']];
                $budanMoney = empty($mzBDMoneyAllTwo[$value['shop_id']])?0:$mzBDMoneyAllTwo[$value['shop_id']];

            }else{
                //门店
                $newsXDMoney = empty($shopXDMoneyAllOne[$value['shop_id']])?0:$shopXDMoneyAllOne[$value['shop_id']];
                $budanMoney = empty($shopBDMoneyAllTwo[$value['shop_id']])?0:$shopBDMoneyAllTwo[$value['shop_id']];
            }

            $totalNewAmount +=$newsXDMoney;
            $totalRepairAmount +=$budanMoney;


		}

		$list['newOrder'] = $totalNewAmount;
		$list['repairOrder'] = $totalRepairAmount;

		return $list;

	}


}
